import sqlite3
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
from datetime import date, datetime, timedelta
import os
from PIL import Image
import tempfile
from database import (add_checkin_record, delete_analysis_result, delete_planting_schedule, 
                     get_due_reminders, get_electronic_crop, get_planting_schedules, get_user_resources, init_db, plant_electronic_crop, 
                     save_analysis_result, get_history, get_health_trend, 
                     save_planting_schedule, update_electronic_crop, update_planting_schedule, update_user_resources)
from silican_api import SilicanAPI
from io import BytesIO

import time
from weather_api import WeatherAPI

# 初始化数据库
init_db()

# 应用配置
st.set_page_config(
    page_title="农作物健康检测系统",
    page_icon="🌱",
    layout="wide"
)

# 初始化会话状态
if 'api_key' not in st.session_state:
    st.session_state.api_key = ""

if 'history' not in st.session_state:
    st.session_state.history = get_history()

# 初始化种植计划相关会话状态
if 'extracted_events' not in st.session_state:
    st.session_state.extracted_events = []
if 'planting_advice' not in st.session_state:
    st.session_state.planting_advice = ""
if 'selected_crop_for_advice' not in st.session_state:
    st.session_state.selected_crop_for_advice = None


# 侧边栏
with st.sidebar:
    st.title("🌱 农作物种植管理系统")
    
    # API密钥输入
    api_key = st.text_input("硅基流动API密钥", type="password", value=st.session_state.api_key)
    if api_key:
        st.session_state.api_key = api_key
        st.success("API密钥已设置")
    else:
        st.warning("请输入API密钥以使用分析功能")
    
    # 导航
    page = st.radio("导航", ["图片分析", "视频分析", "农业问答助手","历史记录", "健康趋势","种植计划","天气预警","电子农场"])
    
    # 使用说明
    st.divider()
    with st.expander("使用说明"):
        st.markdown("""
        1. 在侧边栏输入硅基流动API密钥
        2. 上传农作物图片或视频
        3. 查看分析结果和建议
        4. 在历史记录中查看过往分析
        5. 在健康趋势中查看作物状态变化
        6. 在种植计划中管理农事日程与系统提醒
        """)
# 系统内提醒检查函数
def check_reminders():
    """检查到期提醒并在侧边栏显示"""
    due_reminders = get_due_reminders()
    if due_reminders:
        reminder_count = len(due_reminders)
        st.sidebar.warning(f"⚠️ 有 {reminder_count} 个农事活动已到期")
        # 展开显示详情
        with st.sidebar.expander("查看到期活动"):
            for idx, reminder in enumerate(due_reminders, 1):
                st.write(f"{idx}. **{reminder['crop_type']}** - {reminder['activity']}")
                st.write(f"   计划日期：{reminder['custom_date'] or '未设置'}")
                st.write("---")
    else:
        st.sidebar.success("✅ 暂无到期的农事提醒")    
    # 系统内到期提醒
    check_reminders()


# 主内容区域
if page == "图片分析":
    st.header("农作物图片分析")
    
    uploaded_file = st.file_uploader("上传农作物图片", type=['jpg', 'jpeg', 'png'])
    
    if uploaded_file is not None:
        # 显示上传的图片
        image = Image.open(uploaded_file)
        st.image(image, caption="上传的农作物图片", use_column_width=True)
        
        # 临时保存图片
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            image.save(tmp_file.name)
            image_path = tmp_file.name
        
        # 分析按钮
        if st.button("分析图片") and st.session_state.api_key:
            with st.spinner("分析中..."):
                # 初始化API
                api = SilicanAPI(st.session_state.api_key)
                
                # 分析图片
                result = api.detect_crop_health(image_path)
                
                # 显示结果
                col1, col2 = st.columns(2)
                
                with col1:
                    st.subheader("分析结果")
                    st.metric("作物类型", result["crop_type"])
                    if result["health_status"] == "健康":
                        st.metric("健康状态", "健康", delta="良好", delta_color="normal")
                    else:
                        st.metric("健康状态", "不健康", delta="需关注", delta_color="inverse")
                    st.metric("置信度", f"{result['confidence']*100:.1f}%")
                
                with col2:
                    st.subheader("详细描述")
                    st.info(result["description"])
                
                st.subheader("建议措施")
                st.success(result["suggestions"])
                
                # 保存到数据库
                save_analysis_result(
                    image_path=uploaded_file.name,
                    crop_type=result["crop_type"],
                    health_status=result["health_status"],
                    confidence=result["confidence"],
                    description=result["description"],
                    suggestions=result["suggestions"]
                )
                
                # 更新历史记录
                st.session_state.history = get_history()
        
        # 清理临时文件
        os.unlink(image_path)
    
    elif not st.session_state.api_key:
        st.warning("请先在侧边栏输入API密钥")


elif page == "视频分析":
    st.header("农作物视频分析")
    
    uploaded_file = st.file_uploader("上传农作物视频", type=['mp4', 'avi', 'mov', 'mkv'])
    
    if uploaded_file is not None:
        # 显示上传的视频
        st.video(uploaded_file)
        
        # 分析选项
        col1, col2 = st.columns(2)
        with col1:
            sample_rate = st.slider("采样频率(秒)", min_value=1, max_value=10, value=3, 
                                   help="从视频中每隔多少秒提取一帧进行分析")
        with col2:
            max_frames = st.slider("最大分析帧数", min_value=1, max_value=20, value=5,
                                  help="最多分析多少帧视频")
        
        # 分析按钮
        if st.button("分析视频") and st.session_state.api_key:
            with st.spinner("视频分析中，这可能需要一些时间..."):
                # 初始化API
                api = SilicanAPI(st.session_state.api_key)
                
                # 临时保存视频
                with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_file:
                    tmp_file.write(uploaded_file.getvalue())
                    video_path = tmp_file.name
                
                cap = None
                try:
                    # 提取视频帧
                    import cv2
                    cap = cv2.VideoCapture(video_path)
                    if not cap.isOpened():
                        st.error("无法打开视频文件")
                        st.stop()
                    
                    fps = cap.get(cv2.CAP_PROP_FPS)
                    frame_interval = int(sample_rate * fps)
                    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                    
                    # 计算预期的最大分析帧数
                    expected_frames = min(max_frames, total_frames // frame_interval)
                    if expected_frames == 0:
                        expected_frames = 1  # 确保至少有一帧
                    
                    # 存储分析结果
                    all_results = []
                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    
                    frames_analyzed = 0
                    frame_count = 0
                    
                    while cap.isOpened() and frames_analyzed < max_frames:
                        ret, frame = cap.read()
                        if not ret:
                            break
                            
                        # 按间隔采样
                        if frame_count % frame_interval == 0:
                            # 临时保存帧图像
                            frame_path = f"temp_frame_{frames_analyzed}.jpg"
                            cv2.imwrite(frame_path, frame)
                            
                            # 分析当前帧
                            status_text.text(f"分析第 {frames_analyzed + 1}/{expected_frames} 帧...")
                            result = api.detect_crop_health(frame_path)
                            all_results.append(result)
                            
                            # 更新进度
                            frames_analyzed += 1
                            progress_value = min(frames_analyzed / expected_frames, 1.0)
                            progress_bar.progress(progress_value)
                            
                            # 删除临时帧文件
                            try:
                                os.unlink(frame_path)
                            except PermissionError:
                                pass
                            
                        frame_count += 1
                    
                    # 汇总分析结果
                    if all_results:
                        avg_confidence = sum(r['confidence'] for r in all_results) / len(all_results)
                        crop_types = [r['crop_type'] for r in all_results]
                        main_crop_type = max(set(crop_types), key=crop_types.count)
                        health_statuses = [r['health_status'] for r in all_results]
                        overall_health = "健康" if all(status == "健康" for status in health_statuses) else "不健康"
                        all_suggestions = "\n".join([f"- {r['suggestions']}" for r in all_results[:3]])
                        
                        # 显示汇总结果
                        st.subheader("视频分析汇总结果")
                        col1, col2, col3 = st.columns(3)
                        with col1:
                            st.metric("主要作物类型", main_crop_type)
                        with col2:
                            st.metric("整体健康状态", overall_health)
                        with col3:
                            st.metric("平均置信度", f"{avg_confidence*100:.1f}%")
                        
                        # 显示详细结果
                        st.subheader("各帧分析详情")
                        for i, result in enumerate(all_results):
                            with st.expander(f"第{i+1}帧 - {result['crop_type']} - {result['health_status']}"):
                                col1, col2 = st.columns(2)
                                with col1:
                                    st.write(f"**作物类型:** {result['crop_type']}")
                                    st.write(f"**健康状态:** {result['health_status']}")
                                    st.write(f"**置信度:** {result['confidence']*100:.1f}%")
                                with col2:
                                    st.write("**描述:**")
                                    st.info(result['description'][:200] + "..." if len(result['description']) > 200 else result['description'])
                        
                        st.subheader("综合建议")
                        st.success(all_suggestions)
                        
                        # 保存到数据库
                        save_analysis_result(
                            image_path=f"视频: {uploaded_file.name}",
                            crop_type=main_crop_type,
                            health_status=overall_health,
                            confidence=avg_confidence,
                            description=f"视频分析汇总，共分析{len(all_results)}帧",
                            suggestions=all_suggestions
                        )
                        
                        # 更新历史记录
                        st.session_state.history = get_history()
                    
                except Exception as e:
                    st.error(f"视频分析出错: {str(e)}")
                    import traceback
                    st.text(traceback.format_exc())
                
                finally:
                    # 释放资源
                    if cap is not None:
                        cap.release()
                    try:
                        if os.path.exists(video_path):
                            os.unlink(video_path)
                    except PermissionError:
                        st.warning("无法删除临时视频文件，稍后将自动清理")
    
    elif not st.session_state.api_key:
        st.warning("请先在侧边栏输入API密钥")


elif page == "历史记录":
    st.header("分析历史记录")
    
    if st.button("刷新历史记录"):
        st.session_state.history = get_history(20)
    
    history_data = st.session_state.history
    
    if history_data:
        df = pd.DataFrame(history_data)
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        
        # 显示历史记录
        for _, row in df.iterrows():
            with st.expander(f"{row['timestamp'].strftime('%Y-%m-%d %H:%M')} - {row['crop_type']} - {row['health_status']}"):
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write(f"**作物类型:** {row['crop_type']}")
                    st.write(f"**健康状态:** {row['health_status']}")
                    st.write(f"**置信度:** {row['confidence']*100:.1f}%")
                
                with col2:
                    st.write(f"**文件名:** {row['image_path']}")
                
                st.write("**描述:**")
                st.info(row['description'])
                
                st.write("**建议:**")
                st.success(row['suggestions'])
                
                # 删除按钮
                if st.button(f"删除记录", key=f"delete_{row['id']}"):
                    delete_analysis_result(row['id'])
                    st.success("记录已删除")
                    st.session_state.history = get_history(20)
                    st.rerun()
    else:
        st.info("暂无历史记录")


elif page == "健康趋势":
    st.header("作物健康趋势分析")
    
    history_data = st.session_state.history
    if history_data:
        crop_types = list(set([item['crop_type'] for item in history_data]))
        selected_crop = st.selectbox("选择作物类型", ["全部"] + crop_types)
        
        # 获取趋势数据
        trend_data = get_health_trend(selected_crop if selected_crop != "全部" else None)
        
        if trend_data:
            df = pd.DataFrame(trend_data)
            df['timestamp'] = pd.to_datetime(df['timestamp'])
            df['health_value'] = df['health_status'].apply(lambda x: 1 if x == '健康' else 0)
            
            # 绘制趋势图
            fig = px.line(df, x='timestamp', y='health_value', 
                         title=f'{selected_crop}健康状态变化趋势',
                         labels={'health_value': '健康状态', 'timestamp': '时间'})
            fig.update_yaxes(tickvals=[0, 1], ticktext=['不健康', '健康'])
            st.plotly_chart(fig, use_container_width=True)
            
            # 显示统计数据
            col1, col2, col3 = st.columns(3)
            healthy_count = len(df[df['health_status'] == '健康'])
            total_count = len(df)
            
            with col1:
                st.metric("总检测次数", total_count)
            with col2:
                st.metric("健康次数", healthy_count)
            with col3:
                st.metric("健康比例", f"{healthy_count/total_count*100:.1f}%" if total_count > 0 else "0%")
        else:
            st.info("暂无趋势数据")
    else:
        st.info("暂无历史记录，无法显示趋势")


elif page == "农业问答助手":
    st.header("🌾 农业知识问答助手")
    st.info("您好！我是您的农业知识小助手，可以回答各种农业相关问题。")
    
    # 初始化会话状态
    if 'qa_history' not in st.session_state:
        st.session_state.qa_history = []
    if 'current_question' not in st.session_state:
        st.session_state.current_question = ""
    
    # 文本输入区域
    question = st.text_area(
        "请输入您的农业问题:", 
        height=100, 
        placeholder="例如：水稻常见病害有哪些防治方法？",
        value=st.session_state.current_question,
        key="text_question_input"
    )
    
    # 提交按钮
    if st.button("提交问题") and question:
        if not st.session_state.api_key:
            st.warning("请先在侧边栏输入硅基流动API密钥")
        else:
            with st.spinner("思考中..."):
                try:
                    api = SilicanAPI(st.session_state.api_key)
                    answer = api.agricultural_qa(question)
                    
                    # 保存到历史记录
                    st.session_state.qa_history.append({
                        "question": question,
                        "answer": answer,
                        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M")
                    })
                    
                    # 清空当前问题
                    st.session_state.current_question = ""
                    st.rerun()
                    
                except Exception as e:
                    st.error(f"回答问题失败: {str(e)}")
    
    # 显示问答历史
    if st.session_state.qa_history:
        st.subheader("问答历史")
        for i, qa in enumerate(reversed(st.session_state.qa_history)):
            with st.expander(f"{qa['timestamp']} - {qa['question'][:50]}..."):
                st.markdown(f"**问题:** {qa['question']}")
                st.markdown(f"**回答:** {qa['answer']}")
                
                # 复制功能
                if st.button("复制答案", key=f"copy_{i}"):
                    st.code(qa['answer'], language=None)
                    st.success("答案已复制到剪贴板")
    
    # 常见问题示例
    st.divider()
    st.subheader("💡 常见问题示例")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("水稻病虫害防治", key="rice_disease"):
            st.session_state.current_question = "水稻常见病虫害有哪些，如何防治？"
            st.rerun()
    
    with col2:
        if st.button("肥料使用指南", key="fertilizer_guide"):
            st.session_state.current_question = "不同作物应该如何使用肥料？有什么注意事项？"
            st.rerun()
    
    with col3:
        if st.button("种植季节选择", key="planting_season"):
            st.session_state.current_question = "各种蔬菜的最佳种植季节是什么时候？"
            st.rerun()


elif page == "种植计划":
    st.header("🌾 农作物种植计划管理")
    
    # 1. 生成种植建议
    st.subheader("一、生成种植建议")
    # 选择作物类型
    crop_options = ["水稻", "玉米", "小麦", "番茄", "黄瓜", "大豆", "花生", "油菜", "土豆", "其他"]
    selected_crop = st.selectbox("选择作物类型", crop_options)
    
    # 生成建议按钮
    if st.button("生成种植建议") and st.session_state.api_key:
        with st.spinner("正在生成种植建议..."):
            try:
                api = SilicanAPI(st.session_state.api_key)
                # 生成种植建议
                prompt = f"请为{selected_crop}提供详细的种植计划，包括关键时间节点和农事活动"
                advice = api.generate_planting_advice(selected_crop, prompt)
                # 提取关键事件
                events = api.extract_events_from_advice(advice)
                
                # 保存到会话状态
                st.session_state.extracted_events = events
                st.session_state.planting_advice = advice
                st.session_state.selected_crop_for_advice = selected_crop
                
                # 显示建议和事件
                st.subheader(f"{selected_crop}种植建议")
                st.info(advice)
                
                st.subheader("提取的关键农事事件")
                if events:
                    for i, event in enumerate(events):
                        col1, col2, col3, col4 = st.columns([3, 2, 2, 1])  
                        with col1:
                            st.write(f"**{event['activity']}**")
                        with col2:
                            st.write(f"推荐时间: {event['time_reference']}")
                        with col3:
                            st.write(f"重要性: {event['importance']}")
                        with col4:
                            # 只保留"添加到日程"按钮
                            if st.button("添加", key=f"add_{i}"):
                                save_planting_schedule(
                                    crop_type=selected_crop,
                                    activity=event['activity'],
                                    time_reference=event['time_reference'],
                                    importance=event['importance']
                                )
                                st.success("已添加到种植日程")
                                st.rerun()
                else:
                    st.warning("未能从建议中提取到关键事件")
                    
            except Exception as e:
                st.error(f"生成建议失败: {str(e)}")
    
    # 显示缓存的建议
    elif st.session_state.selected_crop_for_advice == selected_crop and st.session_state.planting_advice:
        st.subheader(f"{selected_crop}种植建议")
        st.info(st.session_state.planting_advice)
        
        st.subheader("提取的关键农事事件")
        if st.session_state.extracted_events:
            for i, event in enumerate(st.session_state.extracted_events):
                col1, col2, col3, col4 = st.columns([3, 2, 2, 1])
                with col1:
                    st.write(f"**{event['activity']}**")
                with col2:
                    st.write(f"推荐时间: {event['time_reference']}")
                with col3:
                    st.write(f"重要性: {event['importance']}")
                with col4:
                    if st.button("添加", key=f"add_cache_{i}"):
                        save_planting_schedule(
                            crop_type=selected_crop,
                            activity=event['activity'],
                            time_reference=event['time_reference'],
                            importance=event['importance']
                        )
                        st.success("已添加到种植日程")
                        st.rerun()
    
    # 2. 我的种植日程管理
    st.divider()
    st.subheader("二、我的种植日程")
    
    # 加载日程数据
    user_schedule = get_planting_schedules()
    
    if user_schedule:
        # 显示到期提醒（系统内）
        due_reminders = get_due_reminders()
        if due_reminders:
            st.warning("📢 到期提醒：以下农事活动已到期，请及时处理！")
            for reminder in due_reminders:
                st.error(f"• {reminder['crop_type']} - {reminder['activity']}（计划日期：{reminder['custom_date'] or '未设置'}）")
        
        # 显示所有日程
        for i, task in enumerate(user_schedule):
            with st.expander(f"{task['crop_type']} - {task['activity']}"):
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write(f"**作物类型:** {task['crop_type']}")
                    st.write(f"**农事活动:** {task['activity']}")
                    st.write(f"**推荐时间:** {task['time_reference']}")
                    st.write(f"**重要性:** {task['importance']}")
                    st.write(f"**当前计划日期:** {task['custom_date'] or '未设置'}")
                    st.write(f"**创建时间:** {task['created_at']}")
                
                with col2:
                    # 只保留日期修改
                    # 处理默认日期
                    default_date = None
                    if task['custom_date']:
                        try:
                            default_date = datetime.strptime(task['custom_date'], "%Y-%m-%d").date()
                        except ValueError:
                            default_date = date.today()
                    else:
                        default_date = date.today()
                    
                    # 日期选择器
                    custom_date = st.date_input(
                        "修改计划日期", 
                        value=default_date,
                        key=f"date_{i}"
                    )
                    
                    # 保存日期按钮
                    if st.button("保存日期", key=f"save_date_{i}"):
                        update_planting_schedule(
                            schedule_id=task['id'],
                            custom_date=custom_date
                        )
                        st.success("计划日期已更新")
                        st.rerun()
                    
                    # 删除按钮
                    if st.button("删除日程", key=f"delete_schedule_{i}"):
                        delete_planting_schedule(task['id'])
                        st.success("已删除该种植日程")
                        st.rerun()
    else:
        st.info("暂无种植日程，请先通过「生成种植建议」添加农事活动")
# 在所有elif页面后添加天气预警页面
# 在所有elif页面后添加天气预警页面
elif page == "天气预警":
    st.header("🌦️ 天气预警与监测")
    
    # 初始化天气API，使用您的密钥
    weather_api = WeatherAPI("c04aae632198966ddb78ba68d9cdf813")
    
    # 天气设置
    with st.expander("天气设置", expanded=True):
        location = st.text_input("城市名称", "北京")
        
        # 获取用户可能种植的作物类型（从历史记录中提取）
        history_data = st.session_state.history
        crop_options = ["全部作物"]
        if history_data:
            crop_types = list(set([item['crop_type'] for item in history_data if item['crop_type'] != "未知作物"]))
            crop_options.extend(crop_types)
        
        selected_crops = st.multiselect(
            "关注的作物类型",
            options=crop_options,
            default=["全部作物"]
        )
        
        alert_types = st.multiselect(
            "关注预警类型",
            ["暴雨", "大风", "寒潮", "干旱", "高温", "冰雹", "霜冻"],
            ["暴雨", "大风", "寒潮"]
        )
        
        if st.button("保存设置"):
            st.session_state.weather_location = location
            st.session_state.selected_crops = selected_crops
            st.session_state.alert_types = alert_types
            st.success("天气设置已保存")
    
    # 获取当前天气
    if st.button("获取天气信息"):
        with st.spinner("获取天气数据中..."):
            current_weather = weather_api.get_current_weather(location)
            weather_alerts = weather_api.get_weather_alerts(location)
            
            if current_weather:
                st.session_state.current_weather = current_weather
                st.session_state.weather_alerts = weather_alerts
                st.session_state.weather_location = location
            else:
                st.error("获取天气数据失败，请检查城市名称是否正确")
    
    # 显示当前天气
    if 'current_weather' in st.session_state:
        current_weather = st.session_state.current_weather
        weather_alerts = st.session_state.weather_alerts
        location = st.session_state.weather_location
        
        st.subheader(f"{location}当前天气")
        col1, col2, col3 = st.columns(3)
        
        with col1:
            temp = current_weather['main']['temp']
            st.metric("温度", f"{temp}°C")
        
        with col2:
            humidity = current_weather['main']['humidity']
            st.metric("湿度", f"{humidity}%")
        
        with col3:
            weather_desc = current_weather['weather'][0]['description']
            st.metric("天气状况", weather_desc)
        
        # 显示天气预报
        st.subheader("未来天气预报")
        forecast = weather_api.get_weather_forecast(location)
        
        if forecast:
            # 简化显示，只显示今天和明天的天气
            from datetime import datetime
            today = datetime.now().date()
            
            forecast_data = []
            for item in forecast['list'][:8]:  # 只显示前8个时间段（24小时）
                time_str = item['dt_txt']
                temp = item['main']['temp']
                desc = item['weather'][0]['description']
                forecast_data.append({"时间": time_str, "温度": temp, "描述": desc})
            
            forecast_df = pd.DataFrame(forecast_data)
            st.dataframe(forecast_df, use_container_width=True)
        else:
            st.info("无法获取天气预报数据")
        
        # 显示天气预警
        st.subheader("天气预警信息")
        if weather_alerts:
            for alert in weather_alerts:
                alert_type = alert.get('event', '未知预警')
                
                # 只显示用户关注的预警类型
                if alert_type not in st.session_state.alert_types:
                    continue
                
                with st.expander(f"⚠️ {alert_type}预警", expanded=True):
                    st.error(f"预警类型: {alert_type}")
                    st.write(f"开始时间: {alert.get('start', '未知')}")
                    st.write(f"结束时间: {alert.get('end', '未知')}")
                    st.write(f"描述: {alert.get('description', '无详细描述')}")
                    
                    # 使用AI模型生成预防建议
                    if st.button(f"生成{alert_type}预防建议", key=f"advice_{alert_type}"):
                        with st.spinner("生成预防建议中..."):
                            # 获取用户关注的作物类型
                            crops = st.session_state.selected_crops
                            if "全部作物" in crops:
                                crops = ["主要农作物"]  # 使用通用描述
                            
                            # 调用硅基流动API生成建议
                            try:
                                api = SilicanAPI(st.session_state.api_key)
                                advice_prompt = f"""你是一名农业专家，请根据以下天气预警信息为{crops}种植提供专业的预防建议：

预警类型: {alert_type}
预警描述: {alert.get('description', '无详细描述')}
预警时间: 从{alert.get('start', '未知')}到{alert.get('end', '未知')}

请提供:
1. 具体的防护措施
2. 建议的操作时间
3. 需要准备的物资
4. 长期应对策略

请用中文回答，内容要详细、实用，适合农民朋友理解:"""
                                
                                advice = api.agricultural_qa(advice_prompt)
                                st.info(f"预防建议: {advice}")
                            except Exception as e:
                                st.error(f"生成建议失败: {str(e)}")
        else:
            st.success("当前暂无天气预警")
    
    else:
        st.info("请点击「获取天气信息」按钮获取最新天气数据")

        
elif page == "电子农场":
    st.header("🌱 电子农场")
    st.info("在这里您可以种植虚拟作物，通过每日打卡获取水滴和肥料，帮助作物成长！")
    
    # 初始化用户资源
    user_resources = get_user_resources()
    electronic_crop = get_electronic_crop()
    
    # 显示用户资源
    col1, col2 = st.columns(2)
    with col1:
        st.metric("💧 水滴", user_resources['water'])
    with col2:
        st.metric("🌱 肥料", user_resources['fertilizer'])
    
    # 每日打卡功能
    st.subheader("每日打卡")
    today = date.today().isoformat()
    
    if user_resources['last_checkin'] == today:
        st.success("✅ 今日已打卡")
    else:
        if st.button("📅 每日打卡"):
            import random
            # 随机奖励：70%概率获得水滴，30%概率获得肥料
            if random.random() < 0.7:
                reward_type = "water"
                reward_amount = random.randint(1, 3)
                new_water = user_resources['water'] + reward_amount
                update_user_resources(1, water=new_water, last_checkin=today)
                st.success(f"🎉 打卡成功！获得 {reward_amount} 滴水滴💧")
            else:
                reward_type = "fertilizer"
                reward_amount = random.randint(1, 2)
                new_fertilizer = user_resources['fertilizer'] + reward_amount
                update_user_resources(1, fertilizer=new_fertilizer, last_checkin=today)
                st.success(f"🎉 打卡成功！获得 {reward_amount} 份肥料🌱")
            
            # 记录打卡
            add_checkin_record(1, today, reward_type, reward_amount)
            st.rerun()
    
    st.divider()
    
    # 电子作物种植区域
    st.subheader("我的电子作物")
    
    if electronic_crop is None:
        # 选择要种植的作物
        crop_options = ["番茄", "水稻", "玉米", "小麦", "黄瓜", "草莓"]
        selected_crop = st.selectbox("选择要种植的作物", crop_options)
        
        if st.button("🌱 开始种植"):
            plant_electronic_crop(selected_crop)
            st.success(f"已开始种植{selected_crop}！")
            st.rerun()
    else:
        # 显示作物状态
        st.write(f"**作物类型:** {electronic_crop['crop_type']}")
        
        # 根据生长阶段显示不同的图片或文字描述
        growth_stages = {
            0: {"name": "种子阶段", "description": "刚刚种下的种子，需要精心照料", "water_need": 3, "fertilizer_need": 1},
            1: {"name": "发芽阶段", "description": "种子已经发芽，长出嫩叶", "water_need": 5, "fertilizer_need": 2},
            2: {"name": "生长阶段", "description": "作物正在快速生长", "water_need": 8, "fertilizer_need": 3},
            3: {"name": "开花阶段", "description": "作物开始开花，即将结果", "water_need": 10, "fertilizer_need": 4},
            4: {"name": "成熟阶段", "description": "作物已经成熟，可以收获了！", "water_need": 0, "fertilizer_need": 0}
        }
        
        current_stage = growth_stages[electronic_crop['growth_stage']]
        next_stage = electronic_crop['growth_stage'] + 1 if electronic_crop['growth_stage'] < 4 else 4
        
        st.write(f"**生长阶段:** {current_stage['name']} ({electronic_crop['growth_stage']+1}/5)")
        st.write(f"**描述:** {current_stage['description']}")
        
        # 显示进度条
        progress_value = min(1.0, (electronic_crop['water_count'] + electronic_crop['fertilizer_count']) / 
                            (current_stage['water_need'] + current_stage['fertilizer_need']))
        st.progress(progress_value)
        
        st.write(f"💧 浇水: {electronic_crop['water_count']}/{current_stage['water_need']}")
        st.write(f"🌱 施肥: {electronic_crop['fertilizer_count']}/{current_stage['fertilizer_need']}")
        
        # 显示作物图片（如果有）
        growth_stage_images = {
            0: "images/seed.png",
            1: "images/sprout.png",
            2: "images/growing.png",
            3: "images/flowering.png",
            4: "images/mature.png"
        }
        
        # 检查图片是否存在，如果存在则显示
        image_path = growth_stage_images.get(electronic_crop['growth_stage'])
        if image_path and os.path.exists(image_path):
            st.image(image_path, width=200)
        else:
            # 如果没有图片，显示一个占位符
            st.info("🌱 作物生长中...")
        
        # 浇水施肥操作
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("💧 浇水", disabled=user_resources['water'] < 1):
                if electronic_crop['water_count'] < current_stage['water_need']:
                    update_user_resources(1, water=user_resources['water'] - 1)
                    update_electronic_crop(1, water_count=electronic_crop['water_count'] + 1)
                    st.success("浇水成功！")
                else:
                    st.warning("当前阶段不需要更多水了")
                st.rerun()
        
        with col2:
            if st.button("🌱 施肥", disabled=user_resources['fertilizer'] < 1):
                if electronic_crop['fertilizer_count'] < current_stage['fertilizer_need']:
                    update_user_resources(1, fertilizer=user_resources['fertilizer'] - 1)
                    update_electronic_crop(1, fertilizer_count=electronic_crop['fertilizer_count'] + 1)
                    st.success("施肥成功！")
                else:
                    st.warning("当前阶段不需要更多肥料了")
                st.rerun()
        
        # 检查是否可以升级到下一阶段
        if (electronic_crop['water_count'] >= current_stage['water_need'] and 
            electronic_crop['fertilizer_count'] >= current_stage['fertilizer_need'] and
            electronic_crop['growth_stage'] < 4):
            
            if st.button("⬆️ 升级到下一阶段"):
                update_electronic_crop(1, growth_stage=next_stage, water_count=0, fertilizer_count=0)
                st.success(f"作物已升级到 {growth_stages[next_stage]['name']}！")
                st.balloons()
                st.rerun()
        
        # 收获作物（最终阶段）
        if electronic_crop['growth_stage'] == 4:
            if st.button("🎉 收获作物"):
                # 根据作物类型给予奖励
                crop_rewards = {
                    "番茄": {"water": 5, "fertilizer": 3},
                    "水稻": {"water": 3, "fertilizer": 5},
                    "玉米": {"water": 4, "fertilizer": 4},
                    "小麦": {"water": 4, "fertilizer": 4},
                    "黄瓜": {"water": 6, "fertilizer": 2},
                    "草莓": {"water": 2, "fertilizer": 6}
                }
                
                reward = crop_rewards.get(electronic_crop['crop_type'], {"water": 5, "fertilizer": 5})
                new_water = user_resources['water'] + reward['water']
                new_fertilizer = user_resources['fertilizer'] + reward['fertilizer']
                
                update_user_resources(1, water=new_water, fertilizer=new_fertilizer)
                plant_electronic_crop(electronic_crop['crop_type'])  # 重新种植
                
                st.success(f"收获成功！获得 {reward['water']} 滴水滴和 {reward['fertilizer']} 份肥料！")
                st.balloons()
                st.rerun()
    
    st.divider()
    
    # 显示打卡历史
    st.subheader("打卡历史")
    conn = sqlite3.connect('crop_health.db')
    checkin_history = pd.read_sql_query(
        "SELECT checkin_date, reward_type, reward_amount FROM checkin_history ORDER BY checkin_date DESC LIMIT 10", 
        conn
    )
    conn.close()
    
    if not checkin_history.empty:
        st.dataframe(checkin_history)
    else:
        st.info("暂无打卡记录")


# 在适当位置添加定时检查功能
def check_weather_alerts():
    """检查天气预警"""
    if hasattr(st.session_state, 'weather_location'):
        weather_api = WeatherAPI("c04aae632198966ddb78ba68d9cdf813")
        alerts = weather_api.get_weather_alerts(st.session_state.weather_location)
        
        if alerts:
            # 在侧边栏显示预警通知
            alert_count = len(alerts)
            st.sidebar.error(f"⚠️ 有 {alert_count} 个天气预警")
            
            # 展开显示详情
            with st.sidebar.expander("查看天气预警"):
                for idx, alert in enumerate(alerts, 1):
                    alert_type = alert.get('event', '未知预警')
                    st.write(f"{idx}. **{alert_type}**预警")
                    st.write(f"   描述: {alert.get('description', '无详细描述')[:50]}...")
                    st.write("---")



# 在侧边栏适当位置调用
check_weather_alerts()


# 页脚
st.divider()
st.caption("农作物种植管理系统© 2025")